/************************************
* 4、编写一个算法，删除线性链表H中所有重复值的结点，
* 使得每个不同的元素值只保留一个结点。
*************************************/


#include<stdio.h>
#include<malloc.h>

struct NODE;
typedef struct NODE node;
struct NODE{int data;node* next;};

void print_linkedlist(const node* p){
    p=p->next;
    while(p){printf("%d ",p->data);p = p->next;}
    putchar('\n');
}

// add data to the end tof the list no sort
void append(node* h,int data){
    while(h->next)h=h->next;
    h->next = malloc(sizeof(node));
    h = h->next;
    h->data = data;
    h->next = NULL;
}

// make unique
void unique(node* h){
    if(h->next==NULL)return;
    node*p,*q;
    p = h->next;
    while(p->next){
        q = h->next;
        while(1){
            if(q->data == p->next->data){
                q = p->next;
                p->next = q->next;
                free(q);
                break;
            }else q = q->next;
            if(q == p->next){p = p->next;break;}
        }
    }
}


int main(){
    node head;
    node* h = &head;
    h->data = 11;
    h->next = NULL;

    int i = 0;
    int A[11] = {1,7,3,4,5,4,3,2,1,5,6};

    for(i=0;i<h->data;i++)append(h,A[i]);
    printf("List: ");print_linkedlist(h);

    unique(h);
    printf("After unique: ");print_linkedlist(h);

    // clean up
    node* p;
    while(h->next){p = h;h=h->next;free(p);}
    return 0;
}
